//
//  TYPersistenceController.m
//  TYTianJingUnicom
//
//  Created by liboxiang on 2018/5/7.
//  Copyright © 2018年 dingjianjaja. All rights reserved.
//

#import "TYPersistenceController.h"

static TYPersistenceController *persistenceController = nil;

@interface TYPersistenceController()

@property (strong, nonatomic) NSURL *sqliteUrl;

@end

@implementation TYPersistenceController

+ (instancetype)shareInstance
{
    return persistenceController;
}

+ (instancetype)createtWithSqliteName:(NSString *)sqliteName modelName:(NSString *)modelName userID:(NSString *)userID
{
    NSURL *userFolder = [TYPersistenceController createDocFolder:userID];
    NSURL *sqliteUrl = [userFolder URLByAppendingPathComponent:sqliteName];
    NSLog(@"%@",sqliteUrl);
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
    persistenceController = [[self alloc] initWithStoreURL:sqliteUrl modelURL:modelURL];
    persistenceController.sqliteUrl = sqliteUrl;
    return persistenceController;
}

+ (NSURL *)createDocFolder:(NSString *)folderName
{    
    NSURL *docURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *folderUrl = [docURL URLByAppendingPathComponent:folderName];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:folderUrl.path isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) )
    {
        [fileManager createDirectoryAtPath:folderUrl.path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return folderUrl;
}

+ (BOOL)saveAndWait
{
    __block NSError *tmpError = nil;
    [[TYPersistenceController shareInstance] saveContextAndWait:YES completion:^(NSError *error) {
        tmpError = error;
    }];
    if (tmpError) {
        return NO;
    }
    else {
        return YES;
    }
}

@end
